package com.pw.lit.controller;

import com.pw.lit.bean.*;
import com.pw.lit.service.BlogService;
import com.pw.lit.service.LabelsService;
import com.pw.lit.service.SearchHistoryService;
import com.pw.lit.service.UserService;
import com.pw.lit.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class IndexController {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private LabelsService labelsService;

    @Autowired
    private SearchHistoryService searchHistoryService;

    @RequestMapping(value = {"/index", ""})
    public String index(Model model) {
        List<User> users = getUsers();
        List<Blog> blogs = getBlogs();
        List<User> bloguer = new ArrayList<>();
        for (Blog b : blogs) {
            bloguer.add(userService.selectByPrimaryKey(b.getId()));
        }
        users.sort(Comparator.comparing(User::getBlogNumber).reversed());
        model.addAttribute("users", users);
        model.addAttribute("blogs", blogs);
        model.addAttribute("bloguser", bloguer);
        return "index";
    }

    public List<User> getUsers() {
        UserExample userExample = new UserExample();
        UserExample.Criteria usercriteria = userExample.createCriteria();
        usercriteria.andFansIsNotNull();
        userExample.setOrderByClause("FOLLOWS desc");
        return userService.selectByExample(userExample);
    }

    public List<Blog> getBlogs() {
        BlogExample blogExample = new BlogExample();
        BlogExample.Criteria criteria = blogExample.createCriteria();
        criteria.andBidIsNotNull();
        blogExample.setOrderByClause("BID desc");
        return blogService.selectByExample(blogExample);
    }

    //退出
    @RequestMapping("/exit")
    public String exit(HttpSession session) {
        session.invalidate();
        return "redirect:index";
    }

    //清除session
    @RequestMapping("/clean")
    public String clean(HttpSession session) {
        session.invalidate();
        return "redirect:index";
    }

    //上传头像
    @ResponseBody
    @RequestMapping("/uploadHead")
    public Map upload(MultipartFile file, HttpSession session) {

        String prefix = "";
        String dateStr = "";
        //保存上传
        OutputStream out = null;
        InputStream fileInput = null;
        try {
            if (file != null) {
                String originalName = file.getOriginalFilename();
                prefix = originalName.substring(originalName.lastIndexOf(".") + 1);
                Date date = new Date();
                String uuid = UUID.randomUUID() + "";
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                dateStr = simpleDateFormat.format(date);
                String filepath = "src/main/resources/static/layui/images/head-pic/" + dateStr + "/" + uuid + "." + prefix;

                File files = new File(filepath);
                //打印查看上传路径
                System.out.println(filepath);

                File fullPath = new File(files.getAbsolutePath());

                if (!files.getParentFile().exists()) {
                    files.getParentFile().mkdirs();
                }
                file.transferTo(fullPath);
                Map<String, Object> map2 = new HashMap<>();
                Map<String, Object> map = new HashMap<>();
                map.put("code", 0);
                map.put("msg", "");
                map.put("data", map2);
                map2.put("src", "/layui/images/head-pic/" + dateStr + "/" + uuid + "." + prefix);
                User user = (User) session.getAttribute("user");
                user.setImg(map2.get("src").toString());
                userService.updateByPrimaryKey(user);
                return map;
            }

        } catch (Exception e) {
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (fileInput != null) {
                    fileInput.close();
                }
            } catch (IOException e) {
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 1);
        map.put("msg", "");
        return map;
    }

    //不同标签展示blog
    @RequestMapping("/selectbylabels/{label}")
    @ResponseBody
    public Map<String, Object> selectbylabels(@PathVariable("label") String label) {
        Map<String, Object> map = new HashMap<>();
        LabelsExample example = new LabelsExample();
        LabelsExample.Criteria criteria = example.createCriteria();
        criteria.andLabelEqualTo(label);
        try {
            List<Labels> labelsList = labelsService.selectByExample(example);
            List<Blog> blogList = new ArrayList<>();
            for (Labels l : labelsList) {
                blogList.add(blogService.selectByPrimaryKey(l.getBid()));
            }
            List<User> userList = new ArrayList<>();
            for (Blog b : blogList) {
                userList.add(userService.selectByPrimaryKey(b.getId()));
            }
            map.put("blogs", blogList);
            map.put("users", userList);
            map.put("msg", "该标签暂时没有内容!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "错误，请重试!");
        }
        return map;
    }

    //搜索功能
    @RequestMapping("/search")
    public String search(HttpSession session,
                         Model model,
                         @RequestParam("select") String name) {
        Search(session, model, name);
        return "FrontPages/blog/blog-search";
    }

    @RequestMapping("/searchbyhis/{select}")
    public String searchbyhis(HttpSession session,
                              Model model,
                              @PathVariable("select") String name) {
//        BlogExample example = new BlogExample();
//        BlogExample.Criteria criteria = example.createCriteria();
//        criteria.andTitleLike("%" + name + "%");
//        List<Blog> blogs = blogService.selectByExample(example);
//        model.addAttribute("blogs", blogs);
//        List<User> bloguer = new ArrayList<>();
//        for (Blog b : blogs) {
//            bloguer.add(userService.selectByPrimaryKey(b.getId()));
//        }
//        model.addAttribute("bloguser", bloguer);
//        if (session.getAttribute("user") != null) {
//            User user = (User) session.getAttribute("user");
//            addSearchHistory(user.getId(), name);
//            model.addAttribute("shistory", getSearchHistory(user));
//        }
//        if (blogs.size() == 0) {
//            model.addAttribute("msg", "暂时还没有你要找的内容！");
//        }
        Search(session, model, name);
        return "FrontPages/blog/blog-search";
    }

    public Model Search(HttpSession session,
                        Model model,
                        String name) {
        BlogExample example = new BlogExample();
        BlogExample.Criteria criteria = example.createCriteria();
        criteria.andTitleLike("%" + name + "%");

        BlogExample example2 = new BlogExample();
        BlogExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andContentLike("%" + name + "%");

        List<Blog> blogs = blogService.selectByExample(example);
        List<Blog> blogs2 = blogService.selectByExample(example2);

        List bid = new ArrayList<>();
        for (Blog b : blogs) {
            bid.add(b.getBid());
        }
        for (Blog b : blogs2) {
            if (bid.contains(b.getBid())) {
                continue;
            } else {
                blogs.add(b);
            }
        }
        model.addAttribute("blogs", blogs);
        List<User> bloguer = new ArrayList<>();
        for (Blog b : blogs) {
            bloguer.add(userService.selectByPrimaryKey(b.getId()));
        }
        model.addAttribute("bloguser", bloguer);
        if (session.getAttribute("user") != null) {
            User user = (User) session.getAttribute("user");
            addSearchHistory(user.getId(), name);
            model.addAttribute("shistory", getSearchHistory(user));
        }
        if (blogs.size() == 0) {
            model.addAttribute("msg", "暂时还没有你要找的内容！");
        }
        return model;
    }

    //展示搜索历史
    public List<SearchHistory> getSearchHistory(User user) {
        SearchHistoryExample example = new SearchHistoryExample();
        SearchHistoryExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(user.getId());
        criteria.andIdIsNotNull();
        example.setOrderByClause("SID desc");
        return searchHistoryService.selectByExample(example);
    }

    //添加搜索历史
    public boolean addSearchHistory(int id, String content) {

        SearchHistoryExample example=new SearchHistoryExample();
        SearchHistoryExample.Criteria criteria=example.createCriteria();
        criteria.andIdEqualTo(id);
        criteria.andContentEqualTo(content);
        if(searchHistoryService.selectByExample(example).size()!=0){
            return true;
        }else {
            SearchHistory searchHistory = new SearchHistory();
            searchHistory.setId(id);
            searchHistory.setContent(content);
            try {
                searchHistoryService.insert(searchHistory);
                System.out.println("添加搜索历史成功!");
                return true;
            } catch (Exception e) {
                System.out.println("添加搜索历史失败!");
                return false;
            }
        }

    }

    //删除历史记录
    @RequestMapping("/delShis/{sid}")
    @ResponseBody
    public String delShis(@PathVariable("sid") String sid) {
        try {
            searchHistoryService.deleteByPrimaryKey(Integer.parseInt(sid));
            return "删除成功！";
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败！";
        }
    }

    //清空历史记录
    @RequestMapping("/cleanShis")
    @ResponseBody
    public String cleanShis(@RequestParam("li") String li) {
        String[] tip = li.split(",");
        if (tip.length != 0) {
            for (String l : tip) {
                searchHistoryService.deleteByPrimaryKey(Integer.parseInt(l));
            }
            return "清空成功!";
        } else {
            return "没有搜索历史可以清理!";
        }
    }
}
